package com.gydz.interferencenetworkmanagement.common.netty.server;

import com.gydz.interferencenetworkmanagement.common.netty.handler.NettyServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.springframework.stereotype.Component;

@Component
public class UdpNettyServer {

    public static void main(String[] args) {
        UdpNettyServer udpNettyServer = new UdpNettyServer();
        udpNettyServer.run(9020);
    }
    public void run(int port) {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        System.out.println("准备运行端口：" + port);
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup)     //配置现场模型
                .channel(NioDatagramChannel.class)      //配置IO模型
                .option(ChannelOption.SO_BROADCAST,true)    //设置广播模式
                .handler(new ChannelInitializer<NioDatagramChannel>() {
                    @Override
                    protected void initChannel(NioDatagramChannel nioDatagramChannel) {
                        nioDatagramChannel.pipeline().addLast(new NettyServerHandler());
                    }
                });
        bind(bootstrap, port);

    }

    //实现绑定重新绑定方法
        private  void bind(final Bootstrap bootstrap, final int port) {
        bootstrap.bind(port).addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                if (future.isSuccess()) {
                    System.out.println("端口绑定成功");
                } else {
                    System.out.println(port + "端口绑定失败,重新绑定" + port + 1);
                    bind(bootstrap, port + 1);
                }
            }
        });
    }




}
